package com.zt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zt.dto.CourseDto;


import com.zt.entity.Courses;
import com.zt.entity.Result;
import com.zt.entity.Teachers;
import com.zt.service.CoursesService;
import com.zt.service.TeachersService;
import com.zt.service.FileUploadService;
import io.minio.MinioClient;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

/*
 *云计算
 *魏子纹
 *2025/7/1
 */
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CoursesService courseService;

    @Autowired
    private TeachersService teachersService;

    @Autowired
    MinioClient minioClient;

    @PostMapping("/list")
    public Result list(@RequestBody CourseDto courseDto){
        IPage<Courses> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(courseDto.getPageNum(), courseDto.getPageSize());
        if (courseDto.getStatus() == null &&  (courseDto.getName() == null || courseDto.getName().isEmpty()))  {
            // 无条件，查询所有
            List<Courses> list = courseService.page(page).getRecords();


            for (Courses courses : list) {
                Teachers teachers = teachersService.getById(courses.getTeacherId());
                courses.setTeacherName(teachers.getName());
            }



            return Result.success("查询成功",page);
        }

        // 条件查询
        QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(courseDto.getStatus() != null ,"status",courseDto.getStatus()) ;
        // 修正：使用 courseDto.getName() 进行判空检查
        queryWrapper.like(!courseDto.getName().equals("") && !courseDto.getName().isEmpty(), "title", courseDto.getName());
        List<Courses> coursesList = courseService.list(queryWrapper);
        for (Courses courses : coursesList) {
            Teachers teachers = teachersService.getById(courses.getTeacherId());
            courses.setTeacherName(teachers.getName());
        }

        return Result.success("查询成功",coursesList);


    }

    /**
     * 切换课程上下架状态
     * @param id 课程ID
     * @return 操作结果
     */
    @PutMapping("/{id}/toggle-status")
    public Result toggleCourseStatus(@PathVariable("id") Integer id) {
        try {
            System.out.println("切换课程状态，课程ID: " + id);

            if (id == null || id <= 0) {
                return Result.error("课程ID无效");
            }

            // 查询当前课程信息
            Courses course = courseService.getById(id);
            if (course == null) {
                return Result.error("课程不存在");
            }

            // 切换状态：1 -> 0, 0 -> 1
            int newStatus = course.getStatus() == 1 ? 0 : 1;
            course.setStatus(newStatus);

            // 更新课程状态
            boolean updated = courseService.updateById(course);
            if (!updated) {
                return Result.error("更新课程状态失败");
            }

            String statusText = newStatus == 1 ? "已上架" : "已下架";
            Map<String, Object> response = new HashMap<>();
            response.put("id", course.getId());
            response.put("status", newStatus);
            response.put("message", "课程状态更新成功：" + statusText);

            return Result.success("操作成功", response);
        } catch (Exception e) {
            System.out.println("切换课程状态异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("服务器内部错误，请重试");
        }
    }


    private static String COVER_IMAGE;

    @Autowired
    private FileUploadService fileUploadService;

    @PostMapping("/upload")
    public Result uploadCourseCover(MultipartFile file){
        try {
            String imageUrl = fileUploadService.uploadCourseCover(file);
            COVER_IMAGE = imageUrl; // 保存到静态变量供后续使用
            return Result.success("上传成功", imageUrl);
        } catch (Exception e) {
            return Result.error("上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/add")
    @SneakyThrows
    public Result add(@RequestBody CourseDto courseDto){
        if (courseDto==null){
            return Result.error("参数错误");
        }
        // 添加课程
        Courses course = new Courses();
        course.setPrice(courseDto.getPrice());
        course.setDescription(courseDto.getDescription());
        course.setCoverImage(courseDto.getCoverUrl());
        course.setTitle(courseDto.getName());
        course.setTeacherId(courseDto.getTeacherId());
        course.setCreatedAt(new Date());
        boolean result = courseService.save(course);
        if (result){
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    /*
    * 添加课程 todo 这里数据需要清晰，虽然前端页面需要的字段都设置上去了，但是数据库里面的字段仍然有很多的null
    * */
    @PutMapping("/{id}")
    public Result updateCourse(@RequestBody CourseDto courseDto) {
        // 添加课程
        Courses course = new Courses();
        course.setPrice(courseDto.getPrice());
        course.setDescription(courseDto.getDescription());
        course.setCoverImage(courseDto.getCoverUrl());
        course.setTitle(courseDto.getName());
        course.setTeacherId(courseDto.getTeacherId());
        course.setId(courseDto.getId());
        course.setUpdatedAt(new Date());
        boolean update = courseService.updateById(course);
        if (update){
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }


    /**
     * 批量删除课程
     * @param ids 课程ID列表（逗号分隔）
     * @return 操作结果
     */
    @DeleteMapping("{ids}")
    public Result batchDeleteCourse(@PathVariable("ids") String ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的课程");
        }

        try {
            // 将字符串转换为ID列表
            List<Integer> idList = Arrays.stream(ids.split(","))
                    .map(Integer::parseInt)
                    .toList();

            // 调用批量删除方法
            boolean result = courseService.removeByIds(idList);

            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("服务器异常，请重试");
        }
    }



    @GetMapping("/category/tree")
    public Result getCategoryTree() {
        // 返回分类列表  todo
        return null;
    }

}
